<template>
  <div class="order-list-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>订单管理</h1>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAddOrder">
          <el-icon><Plus /></el-icon> 新增订单
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon> 导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon> 导出
        </el-button>
        <el-dropdown @command="handleBatchCommand">
          <el-button>
            <el-icon><More /></el-icon> 批量操作
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="batchCancel">批量取消</el-dropdown-item>
              <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
              <el-dropdown-item command="batchExport">批量导出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="订单编号">
              <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable>
                <el-option v-for="supplier in suppliers" :key="supplier.id" :label="supplier.name" :value="supplier.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态">
              <el-select v-model="searchForm.status" placeholder="请选择订单状态" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="待审核" value="0"></el-option>
                <el-option label="已审核" value="1"></el-option>
                <el-option label="已确认" value="2"></el-option>
                <el-option label="已付款" value="3"></el-option>
                <el-option label="已发货" value="4"></el-option>
                <el-option label="已完成" value="5"></el-option>
                <el-option label="已取消" value="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单类型">
              <el-select v-model="searchForm.type" placeholder="请选择订单类型" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="采购订单" value="1"></el-option>
                <el-option label="销售订单" value="2"></el-option>
                <el-option label="退货订单" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="searchForm.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="search-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 订单表格 -->
    <el-card class="table-card">
      <div class="table-container">
        <el-table
          v-loading="tableLoading"
          :data="orderList"
          border
          stripe
          size="medium"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="orderNo" label="订单编号" min-width="140"></el-table-column>
          <el-table-column prop="supplierName" label="供应商" min-width="120"></el-table-column>
          <el-table-column prop="typeName" label="订单类型" width="100"></el-table-column>
          <el-table-column
            prop="status"
            label="订单状态"
            width="100"
          >
            <template #default="scope">
              <el-tag :type="getStatusInfo(scope.row).type">
                {{ getStatusInfo(scope.row).text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="totalAmount"
            label="订单金额"
            width="120"
            formatter="formatCurrency"
          ></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
          <el-table-column prop="creatorName" label="创建人" width="100"></el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown size="small" @command="(command) => handleAction(command, scope.row)">
                <el-button size="small">
                  更多
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="cancel" :disabled="!canCancel(scope.row)">取消订单</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                    <el-dropdown-item command="copy">复制订单</el-dropdown-item>
                    <el-dropdown-item command="print">打印订单</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-card">
      <div class="statistics-container">
        <div class="stat-item">
          <div class="stat-label">总订单数</div>
          <div class="stat-value">{{ statistics.totalOrders }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">今日新增</div>
          <div class="stat-value">{{ statistics.todayNewOrders }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">本月订单</div>
          <div class="stat-value">{{ statistics.monthOrders }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">待处理订单</div>
          <div class="stat-value">{{ statistics.pendingOrders }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">订单总金额</div>
          <div class="stat-value">{{ formatCurrency(statistics.totalAmount) }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import {
  Plus,
  Upload,
  Download,
  More,
  ArrowDown
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

// 路由实例
const router = useRouter();

// 表格加载状态
const tableLoading = ref(false);

// 搜索表单数据
const searchForm = reactive({
  orderNo: '',
  supplierId: '',
  status: '',
  type: '',
  createTime: [] as string[]
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 订单列表数据
const orderList = ref([]);

// 选中的订单
const selectedOrders = ref([]);

// 供应商列表
const suppliers = ref([
  { id: '1', name: '阿里巴巴科技有限公司' },
  { id: '2', name: '腾讯云计算有限公司' },
  { id: '3', name: '华为技术有限公司' },
  { id: '4', name: '百度在线网络技术有限公司' },
  { id: '5', name: '京东科技控股股份有限公司' }
]);

// 统计数据
const statistics = reactive({
  totalOrders: 0,
  todayNewOrders: 0,
  monthOrders: 0,
  pendingOrders: 0,
  totalAmount: 0
});

// 格式化状态显示
const getStatusInfo = (row: any) => {
  const statusMap = {
    '0': { text: '待审核', type: 'info' },
    '1': { text: '已审核', type: 'primary' },
    '2': { text: '已确认', type: 'success' },
    '3': { text: '已付款', type: 'warning' },
    '4': { text: '已发货', type: 'purple' },
    '5': { text: '已完成', type: 'green' },
    '6': { text: '已取消', type: 'danger' }
  };
  return statusMap[row.status] || { text: '未知', type: 'default' };
};

// 格式化金额显示
const formatCurrency = (value: number) => {
  if (!value) return '¥0.00';
  return '¥' + value.toFixed(2);
};

// 检查是否可以取消订单
const canCancel = (row: any) => {
  // 只有待审核、已审核、已确认状态可以取消
  return ['0', '1', '2'].includes(row.status);
};

// 选择项变化
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection;
};

// 搜索订单
const handleSearch = () => {
  pagination.currentPage = 1;
  getOrderList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    orderNo: '',
    supplierId: '',
    status: '',
    type: '',
    createTime: []
  });
  pagination.currentPage = 1;
  getOrderList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  getOrderList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  getOrderList();
};

// 查看订单
const handleView = (row: any) => {
  router.push({ name: 'OrderDetail', params: { id: row.id } });
};

// 编辑订单
const handleEdit = (row: any) => {
  router.push({ name: 'OrderEdit', params: { id: row.id } });
};

// 新增订单
const handleAddOrder = () => {
  router.push({ name: 'OrderAdd' });
};

// 导入订单
const handleImport = () => {
  ElMessage.info('导入功能待实现');
};

// 导出订单
const handleExport = () => {
  ElMessage.info('导出功能待实现');
};

// 批量操作
const handleBatchCommand = (command: string) => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择订单');
    return;
  }

  switch (command) {
    case 'batchCancel':
      handleBatchCancel();
      break;
    case 'batchDelete':
      handleBatchDelete();
      break;
    case 'batchExport':
      handleBatchExport();
      break;
  }
};

// 批量取消
const handleBatchCancel = () => {
  ElMessageBox.confirm('确定要批量取消选中的订单吗？', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('批量取消成功');
      getOrderList();
    }, 1000);
  });
};

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要批量删除选中的订单吗？此操作不可恢复！', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('批量删除成功');
      getOrderList();
    }, 1000);
  });
};

// 批量导出
const handleBatchExport = () => {
  ElMessage.info('批量导出功能待实现');
};

// 订单操作
const handleAction = (command: string, row: any) => {
  switch (command) {
    case 'cancel':
      handleCancelOrder(row);
      break;
    case 'delete':
      handleDeleteOrder(row);
      break;
    case 'copy':
      handleCopyOrder(row);
      break;
    case 'print':
      handlePrintOrder(row);
      break;
  }
};

// 取消订单
const handleCancelOrder = (row: any) => {
  ElMessageBox.confirm(`确定要取消订单 ${row.orderNo} 吗？`, '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '取消中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('订单取消成功');
      getOrderList();
    }, 1000);
  });
};

// 删除订单
const handleDeleteOrder = (row: any) => {
  ElMessageBox.confirm(`确定要删除订单 ${row.orderNo} 吗？此操作不可恢复！`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('订单删除成功');
      getOrderList();
    }, 1000);
  });
};

// 复制订单
const handleCopyOrder = (row: any) => {
  router.push({ name: 'OrderAdd', query: { copyFrom: row.id } });
};

// 打印订单
const handlePrintOrder = (row: any) => {
  ElMessage.info(`打印订单 ${row.orderNo}`);
};

// 获取订单列表
const getOrderList = () => {
  tableLoading.value = true;

  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    const mockData = [];
    const statuses = ['0', '1', '2', '3', '4', '5', '6'];
    const types = ['1', '2', '3'];
    const typeNames = ['采购订单', '销售订单', '退货订单'];

    for (let i = 0; i < pagination.pageSize; i++) {
      const index = (pagination.currentPage - 1) * pagination.pageSize + i + 1;
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      const type = types[Math.floor(Math.random() * types.length)];
      const amount = Math.floor(Math.random() * 100000) + 1000;
      const supplier = suppliers.value[Math.floor(Math.random() * suppliers.value.length)];

      mockData.push({
        id: `ORD${100000 + index}`,
        orderNo: `PO${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(Math.floor(Math.random() * 1000000)).padStart(6, '0')}`,
        supplierId: supplier.id,
        supplierName: supplier.name,
        type: type,
        typeName: typeNames[parseInt(type) - 1],
        status: status,
        totalAmount: amount,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
        creatorName: `用户${Math.floor(Math.random() * 1000)}`,
        remark: `这是订单${index}的备注信息`
      });
    }

    orderList.value = mockData;
    pagination.total = 128; // 模拟总条数
    tableLoading.value = false;

    // 更新统计数据
    updateStatistics();
  }, 800);
};

// 更新统计数据
const updateStatistics = () => {
  statistics.totalOrders = pagination.total;
  statistics.todayNewOrders = Math.floor(Math.random() * 20) + 1;
  statistics.monthOrders = Math.floor(Math.random() * 100) + 30;
  statistics.pendingOrders = Math.floor(Math.random() * 15) + 5;
  statistics.totalAmount = Math.floor(Math.random() * 10000000) + 500000;
};

// 页面加载时初始化
onMounted(() => {
  getOrderList();
});
</script>

<style scoped lang="scss">
.order-list-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  padding: 10px 0;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.table-container {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.statistics-card {
  margin-top: 20px;
}

.statistics-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.stat-item {
  flex: 1;
  min-width: 120px;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-list-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .statistics-container {
    flex-direction: column;
  }

  .stat-item {
    width: 100%;
  }
}
</style>